/**
 * Created by Administrator on 2017/9/6.
 * Copyright 2017-2018 汉威.智慧环保事业部 Limited.
 * All rights reserved.
 */
package com.hw.one.collect.util;


import com.hw.one.collect.base.BaseContextUtil;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.connection.Connection;
import com.rabbitmq.client.Channel;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Component
public class MessageProducer{

    @Resource
    private CachingConnectionFactory connectionFactory = (CachingConnectionFactory) BaseContextUtil.getBean("rabbitConnectionFactory");
    @Resource
    private RabbitAdmin rabbitAdmin = (RabbitAdmin) BaseContextUtil.getBean("rabbitAdmin");

    @Resource
    private RabbitTemplate producerRabbitTemplate = (RabbitTemplate) BaseContextUtil.getBean("producerRabbitTemplate");

    public MessageProducer() {
    }

    public MessageProducer(String routingKey, String message) {
        this.sendMessage(routingKey, message);
    }

    public RabbitTemplate getRabbitTemplate() {
        return this.producerRabbitTemplate;
    }

    public RabbitAdmin getRabbitAdmin() {
        return this.rabbitAdmin;
    }

    /**
     * 发送信息到默认队列中
     *
     * @param message
     */

    public void sendMessage(String message) {
        this.producerRabbitTemplate.convertAndSend(message);
    }

    /**
     * 根据routingKey，发送信息到指定的队列
     *
     * @param routingKey
     * @param message
     */

    public void sendMessage(String routingKey, String message) {
        this.producerRabbitTemplate.convertAndSend("amq.topic", routingKey, message);
    }

    /**
     * 根据exchange和routingKey，发送信息到指定的队列
     *
     * @param routingKey
     * @param message
     */
    public void sendMessage(String exchange, String routingKey, String message) {
        this.producerRabbitTemplate.convertAndSend(exchange, routingKey, message);
    }

    /**
     * 代码History交换，同时发送消息
     *
     * @param exchangeName
     * @param routingKey
     */

    public void sendMessageByHistoryExchange(String exchangeName, String routingKey, String message) {
        Connection connection = this.connectionFactory.createConnection();
        Channel channel = connection.createChannel(true);
        Map<String, Object> args = new HashMap<>();
        args.put("x-recent-history-length", 1);
        try {
            channel.exchangeDeclare(exchangeName, "x-recent-history", true, false, args);
            this.producerRabbitTemplate.convertAndSend(exchangeName, "", message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
